package smartcode;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.transition.Slide;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ExpandableListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.aliang.auto.R;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

import app.auto.AndroidInstance;
import app.auto.runner.base.intf.FunCallback;
import app.auto.runner.base.intf.MapBuilder;
import app.auto.runner.base.utility.ShareAlert;
import app.auto.runner.base.utility.SlideBottomUtil;
import app.auto.runner.base.utility.ToastUtil;
import app.auto.runner.base.widget.FloatLayout;

public class Methods extends AndroidInstance {
    private List<List> childs = new ArrayList<>();
    private List group = new ArrayList<>();
    private ExpandableListviewAdapter methodsAdapter;
    public static MapBuilder animport;
    private String title;
    private SlideBottomUtil slideBottomUtil;

    public Methods setAnimport(MapBuilder animport) {
        Methods.animport = animport;
        return this;
    }

    @Override
    public AndroidInstance use(Object mp, Object... p) {
        return null;
    }

    public Methods setChilds(List<List> childs) {
        this.childs = childs;
        return this;
    }

    public Methods setGroup(List<String> group) {
        this.group = group;
        return this;
    }

    public Methods setMethodsAdapter(ExpandableListviewAdapter methodsAdapter) {
        this.methodsAdapter = methodsAdapter;
        return this;
    }

    public String importclz;

    public Methods setImportclz(String importclz) {
        this.importclz = importclz;
        return this;
    }

    Object result;
    Object clzes;
    FloatLayout selectedFloatLayout;
    Stack objectStack;
    BaseAdapter baseAdapter;

    public Methods setResult(Object result) {
        this.result = result;
        return this;
    }

    public Methods setClzes(Object clzes) {
        this.clzes = clzes;
        return this;
    }

    public Methods setSelectedFloatLayout(FloatLayout selectedFloatLayout) {
        this.selectedFloatLayout = selectedFloatLayout;
        return this;
    }

    public Methods setObjectStack(Stack objectStack) {
        this.objectStack = objectStack;
        return this;
    }

    public Methods setBaseAdapter(BaseAdapter baseAdapter) {
        this.baseAdapter = baseAdapter;
        return this;
    }

    Dialog d;

    boolean slideOrPop;

    public Methods setSlideOrPop(boolean slideOrPop) {
        this.slideOrPop = slideOrPop;
        return this;
    }

    public void addAClz(final boolean newObject) {
        final Context context = getContext();
        try {
            if (result == null || !result.toString().contains(".")) {
                ToastUtil.live(context).center("没有更多方法了");
                if (clzes != null) {
                    if (clzes instanceof Dialog) {

                        ((Dialog) clzes).dismiss();
                        ((Dialog) clzes).cancel();
                    } else if (clzes instanceof PopupWindow) {

                        ((PopupWindow) clzes).dismiss();
                    }

                }
                return;
            }
            final Class clz = Class.forName(result.toString());

            View layout_expandable = LayoutInflater.from(context).inflate(R.layout.activity_expandable, null);
            if (title != null) {
                ((TextView) layout_expandable.findViewById(R.id.title1)).setText(title.toString());
                layout_expandable.findViewById(R.id.title1).setVisibility(View.VISIBLE);
            }

            ((TextView) layout_expandable.findViewById(R.id.title)).setText(result.toString());
            ExpandableListView expandable = layout_expandable.findViewById(R.id.expand_listview);


            expandable = expandable.findViewById(R.id.expand_listview);
            methodsAdapter = new ExpandableListviewAdapter(context, group, childs);
            expandable.setAdapter(methodsAdapter);

            //默认展开第一个数组 spref

            expandable.expandGroup(0);
            expandable.expandGroup(1);
            if (group.size() >= 3) {
                expandable.expandGroup(2);
            }
            if (slideOrPop) {
                int h = ((Activity) context).getWindowManager().getDefaultDisplay().getHeight() / 5 * 3;
                slideBottomUtil = SlideBottomUtil.slideBottom((Activity) getContext(), layout_expandable, h);

            } else {
                d = new AlertDialog.Builder(getContext()).setView(layout_expandable).setCancelable(true).create();
            }
            expandable.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                @SuppressLint("NewApi")
                @RequiresApi(api = Build.VERSION_CODES.M)
                @Override
                public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                    Object m = childs.get(groupPosition).get(childPosition);
                    if (newObject) {
                        if (groupPosition == 0) {
                            clickConstructor(m, clz);
                        } else if (groupPosition == 1) {
                            staticmethods((Method) m, clz);
                        } else if (groupPosition == 2) {
                            if (((Method) m).getParameterCount() == 0) {
                                staticmethods((Method) m, clz);
                            } else {

                            }
                        }


                    } else {
                        if (groupPosition == 0) {

//                            if (m.getParameterCount() > 0) {
//
////                                    List<StringType> stringTypes = VarSelect.popVarsSelect(vars);
//                                //add here
//                                if (clzes != null) {
//                                    clzes.dismiss();
//                                    clzes.cancel();
//                                }
//
//                                type.dismiss();
//                                type.cancel();
//                                stat.dismiss();
//                                stat.cancel();
//                                return;
//                            }
                            staticmethods((Method) m, clz);
                        } else if (groupPosition == 1) {
                            publicDyn(m);
                        }
                    }
                    if (d != null) {
                        d.dismiss();
                        d.cancel();
                    }
                    return false;
                }
            });
            if (slideBottomUtil != null) {
                if (clzes instanceof Dialog) {

                    ((Dialog) clzes).dismiss();
                    ((Dialog) clzes).cancel();
                } else if (clzes instanceof PopupWindow) {

                    ((PopupWindow) clzes).dismiss();
                }
                slideBottomUtil.show((Activity) getContext());
            } else {
                d.show();
            }
            if (true) {//mark
                return;
            }
            List methodList = new ArrayList(Arrays.asList("构造器", "静态方法", "public动态"));
            ShareAlert.get(ShareAlert.class, context).setListsearchEditEnabled(false).listAlert(methodList, new FunCallback() {
                @Override
                public void onCallback(Object result, Object object) {
                    super.onCallback(result, object);
                    final Dialog type = ((Dialog) this.getParam());


                    if (result.toString().equals("构造器")) {
                        ShareAlert.get(ShareAlert.class, context).setListsearchEditEnabled(false).addreplaceEmpty(clz.getPackage().getName() + ".").listAlert(new ArrayList(Arrays.asList(clz.getConstructors())), new FunCallback() {
                            @Override
                            public void onCallback(Object result1, Object object) {
                                super.onCallback(result1, object);
                                //处理重名class;取名
                                clickConstructor(result1, clz);
                                type.dismiss();
                                type.cancel();
                                ((Dialog) this.getParam()).dismiss();
                                ((Dialog) this.getParam()).cancel();


                            }
                        });
                    } else if (result.toString().equals("静态方法")) {
                        List methods = new ArrayList();
                        for (Method m : clz.getMethods()) {
                            if (m.toGenericString().contains("static")) {
                                methods.add(m);
                            }
                        }
                        ShareAlert.get(ShareAlert.class, context).addreplaceEmpty(clz.getPackage().getName() + ".").listAlert(methods, new FunCallback() {
                            @RequiresApi(api = Build.VERSION_CODES.O)
                            @Override
                            public void onCallback(Object result1, Object object) {
                                super.onCallback(result1, object);
                                Dialog stat = (Dialog) this.getParam();
                                Method m = (Method) result1;
                                if (m.getParameterCount() > 0) {

//                                    List<StringType> stringTypes = VarSelect.popVarsSelect(vars);
                                    //add here
                                    if (clzes instanceof Dialog) {

                                        ((Dialog) clzes).dismiss();
                                        ((Dialog) clzes).cancel();
                                    } else if (clzes instanceof PopupWindow) {

                                        ((PopupWindow) clzes).dismiss();
                                    }

                                    type.dismiss();
                                    type.cancel();
                                    stat.dismiss();
                                    stat.cancel();
                                    return;
                                }
                                staticmethods(m, clz);
                                type.dismiss();
                                type.cancel();
                                stat.dismiss();
                                stat.cancel();
                            }
                        });
                    } else if (result.toString().equals("public动态")) {
                        List methods = new ArrayList();
                        for (Method m : clz.getMethods()) {
                            if (!m.toGenericString().contains("static") && m.toGenericString().contains("public")) {
                                methods.add(m);
                            }
                        }
                        ShareAlert.get(ShareAlert.class, context).addreplaceEmpty(clz.getPackage().getName() + ".").listAlert(methods, new FunCallback() {
                            @RequiresApi(api = Build.VERSION_CODES.O)
                            @Override
                            public void onCallback(Object result1, Object object) {
                                super.onCallback(result1, object);

                                Dialog d = (Dialog) this.getParam();

                                publicDyn(result1);
                                type.dismiss();
                                type.cancel();
                                d.dismiss();
                                d.cancel();


                            }
                        });
                    }

                }
            });


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void publicDyn(Object result1) {
        String[] sm = result1.toString().split("\\.");
        Method m = (Method) result1;

        if (m.getParameterCount() == 0) {
            String toadd = "." + sm[sm.length - 1];
            selectedFloatLayout.addLast(toadd);
            objectStack.add(m.getReturnType().getName());
            if (baseAdapter != null) {
                baseAdapter.notifyDataSetChanged();
            }
            if (selectedFloatLayout.hasReturnValue()) {
                selectedFloatLayout.clearReturnValue();
            }
        }
        if (slideOrPop) {
            slideBottomUtil.dismiss();
        } else {
            if (clzes instanceof Dialog) {

                ((Dialog) clzes).dismiss();
                ((Dialog) clzes).cancel();
            } else if (clzes instanceof PopupWindow) {

                ((PopupWindow) clzes).dismiss();
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void staticmethods(Method m, Class clz) {
        String name = "";
        if (animport.get().containsValue(clz.getName())) {
            name = clz.getSimpleName();
        } else {
            if (animport.get().containsKey(clz.getSimpleName())) {
                name = clz.getName();
            } else {
                animport.add(clz.getSimpleName(), clz.getName());
                name = clz.getSimpleName();
            }
        }

        String txt = "." + m.getName() + "()";
        if (objectStack.size() == 0) {
            txt = name + txt;
        }
        selectedFloatLayout.addLast(txt);
        if (selectedFloatLayout.hasReturnValue()) {
            selectedFloatLayout.clearReturnValue();
        }
        if (baseAdapter != null) {
            baseAdapter.notifyDataSetChanged();
        }
        objectStack.add(m.getReturnType().getName());
        if (slideOrPop) {
            slideBottomUtil.dismiss();
        } else {
            if (clzes instanceof Dialog) {

                ((Dialog) clzes).dismiss();
                ((Dialog) clzes).cancel();
            } else if (clzes instanceof PopupWindow) {

                ((PopupWindow) clzes).dismiss();
            }
        }

    }

    private void clickConstructor(Object result1, Class clz) {
        String writtenClzName = "";
        if (animport.get().containsValue(clz.getName())) {

        } else {
            if (animport.get().containsKey(clz.getSimpleName())) {
                String[] writtenClzNameArr = result1.toString().split(" ");
                writtenClzName = writtenClzNameArr[writtenClzNameArr.length - 1];


            } else {

                animport.add(clz.getSimpleName(), clz.getName());
            }
        }
        //data: public explorer.StorageUtil()
        if (TextUtils.isEmpty(writtenClzName)) {
            String[] clzarr = result1.toString().split("\\.");
            writtenClzName = clzarr[clzarr.length - 1];
        }
        //处理重名 class； 取名结束
        selectedFloatLayout.addLast("new " + writtenClzName);
        if (baseAdapter != null) {
            baseAdapter.notifyDataSetChanged();
        }

        objectStack.add(clz.getName());
        if (slideOrPop) {
            slideBottomUtil.dismiss();
        } else {
            if (clzes instanceof Dialog) {

                ((Dialog) clzes).dismiss();
                ((Dialog) clzes).cancel();
            } else if (clzes instanceof PopupWindow) {

                ((PopupWindow) clzes).dismiss();
            }
        }
    }

    public Methods setTitle(String s) {
        this.title = s;
        return this;
    }
}
